// pages/settlement/settlement.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    products:[],
    instantDeliveryProducts: [],  // 即时配送商品列表
    storePickupProducts: [],    // 门店自提商品列表
    vipFlag:false,
    currentId: '', 
    consigneeName: "", 
    consigneePhone: "", 
    currentAddress: "",
    itemArry:'',
    detailFlagId:'',
    totalPrice:'',
    totalOriPrice:'',
    orinDiscount:'',
    couponDiscount:'',
    total_fee:0.00,
    total_discount:0.00,
    goodsList:[],
    showModal: false,
    isDiscountTypeFlag: false,
    isAllDiscountTypeFlag: false,
    isHaveCoupon: false,
    isOnlyCoupon: false,
    modalAnimation: null,
    maskAnimation: null,
    currentCouId:'',
    coupons:[],
    money:0.00,
    selectedIndex: '',
    giftName:'',
    giftUrl:'',
  },
  //获取商品列表
  getProduct:function(){
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/productNew/listBySendType",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{},
      dataType:"json",
      complete:function(result) {
        console.log(9999,result.data.data);
        let data=result.data.data;
        //实现data.sendType 的值为1还是2,分成两个数组
        const instantDeliveryProducts = [];  // 即时配送商品列表
        const storePickupProducts = [];    
        if (data && data.length) {
          data.forEach(product => {
            if (product.sendType === 1) {
              instantDeliveryProducts.push(product);
            } else if (product.sendType === 2) {
              storePickupProducts.push(product);
            }
          });
        }
        _this.setData({
          products:data,
          instantDeliveryProducts: instantDeliveryProducts,
          storePickupProducts: storePickupProducts
        })
      }
    })
  },
  handleSelect: function(e) {
    this.setData({
      selectedIndex: e.currentTarget.dataset.index,
      giftName:e.currentTarget.dataset.type,
      giftUrl:e.currentTarget.dataset.url
    });
  },

  checkAddress() {
    wx.navigateTo({
      url: '/pages/checkAddress/checkAddress?item='+this.data.itemArry+'&addressId='+this.data.currentId+'&currentCouId='+this.data.currentCouId
    })
  },
  showDetail(e){
    const id = e.currentTarget.dataset.id;
    console.log(123,id);
    if(this.data.detailFlagId==id){
      this.setData({
        detailFlagId: ''
      });
    }else{
      this.setData({
        detailFlagId: id
      });
    }
  },
  //点击优惠券
  checkCou(e){
    let id=e.currentTarget.dataset.index;
    let _this=this;
    if(this.data.currentCouId==id){
      id=''
    }
    this.setData({
      currentCouId:id
    })
    console.log(123242,this.data.currentCouId);
  },
  okCou(){
    console.log(1998,this.data.currentCouId===14);
    console.log(1998,this.data.currentCouId==14);
    if(this.data.currentCouId){
      console.log(998,this.data.coupons);
      const coupon=this.data.coupons.find(item => item.id == this.data.currentCouId);
      console.log(998,coupon);
      let discountNum=0;
      let _this=this;
      if(coupon.discountType==5){
        discountNum=(_this.data.totalPrice * (0.12)).toFixed(2)
      }
      if(coupon.discountType==4 || coupon.discountType==6){
        discountNum=coupon.discount
      }
      if(coupon.discountType==9){
        discountNum=(_this.data.totalPrice * (0.12)).toFixed(2)
      }
      if(coupon.discountType==10){
        discountNum=(_this.data.totalPrice * (0.15)).toFixed(2)
      }
      if(coupon.discountType==11){
        discountNum=(_this.data.totalPrice * (0.2)).toFixed(2)
      }
      if(coupon.discountType==12){
        discountNum=(_this.data.totalPrice * (0.25)).toFixed(2)
      }
      this.setData({
        couponDiscount:discountNum,
        total_discount:(parseFloat(_this.data.orinDiscount)+parseFloat(discountNum)).toFixed(2),
        total_fee:((parseFloat(_this.data.totalPrice)-parseFloat(discountNum)).toFixed(2))>0?((parseFloat(_this.data.totalPrice)-parseFloat(discountNum)).toFixed(2)):0,
        showModal:false
      })
      if(!this.data.isOnlyCoupon && this.data.total_fee<39){
        this.setData(
          {
            money:(parseFloat(this.data.total_fee)+parseFloat(10)).toFixed(2),
          }
        )
      }else{
        this.setData({
          money:this.data.total_fee
        })
      }
      
    }else{
      let _this=this;
      this.setData({
        couponDiscount:'',
        total_discount:_this.data.orinDiscount,
        total_fee:_this.data.totalPrice>0?_this.data.totalPrice:0,
        showModal:false
      })
      if(!this.data.isOnlyCoupon && this.data.total_fee<39){
        this.setData(
          {
            money:(parseFloat(this.data.total_fee)+parseFloat(10)).toFixed(2),
          }
        )
      }else{
        this.setData({
          money:this.data.total_fee
        })
      }
    }
    console.log(123456,this.data.total_fee);
    
  },
    //最佳优惠券
   rightCoupons(options){
    //获取优惠券并设置最佳优惠券
    //获取优惠券
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/couponsList",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{phone:wx.getStorageSync('phone')},
      dataType:"json",
      complete:function(result) {
        console.log(33,result.data.data);
        let flag=JSON.parse(options.item).totalPrice >= 88
        let cdata=[]
        // console.log(123545,flag);
        // if(flag){
        //   cdata =result.data.data.filter(item => item.STATUS == 0);
        // }else{
        //   cdata =result.data.data.filter(item => item.STATUS == 0 && item.discountType!=6);
        // }
        cdata =result.data.data.filter(item => item.STATUS == 0 && item.discountType !=16 && item.discountType !=15 && item.discountType !=14 && item.discountType !=13);
        _this.setData({
          coupons:cdata
        })
        if(options.currentCouId){
          _this.setData({
            currentCouId:options.currentCouId
          })
          _this.okCou()
        }
      }
    })
  },

  coupon() {
    wx.navigateTo({
      url: '/pages/coupon/coupon'
    })
  },
        // 2.0打开弹窗
        showModal(e) {
          // 创建动画
          const modalAnimation = wx.createAnimation({
            duration: 300,
            timingFunction: 'ease-out'
          })
          
          const maskAnimation = wx.createAnimation({
            duration: 300,
            timingFunction: 'ease-out'
          })
        
          // 执行动画
          maskAnimation.opacity(1).step()
          modalAnimation.translateY(0).step()
          this.setData({
            showModal: true,
            modalAnimation: modalAnimation.export(),
            maskAnimation: maskAnimation.export()
          })
        },
        
        hideModal() {
          const modalAnimation = wx.createAnimation({
            duration: 250,
            timingFunction: 'ease-in'
          })
          
          const maskAnimation = wx.createAnimation({
            duration: 250,
            timingFunction: 'ease-in'
          })
        
          maskAnimation.opacity(0).step()
          modalAnimation.translateY('100%').step()
        
          this.setData({
            modalAnimation: modalAnimation.export(),
            maskAnimation: maskAnimation.export()
          })
        
          // 延迟隐藏保证动画完成
          setTimeout(() => {
            this.setData({ showModal: false })
          }, 250)
        },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getProduct()
    console.log(19950424,options.currentCouId);
    console.log(123456,JSON.parse(options.item));
    if(options.address){
      console.log(123556,JSON.parse(options.address));
      this.setData({
        currentId: JSON.parse(options.address).currentId, 
        consigneeName: JSON.parse(options.address).consigneeName, 
        consigneePhone: JSON.parse(options.address).consigneePhone, 
        currentAddress: JSON.parse(options.address).currentAddress, 
      })
    }
    
    this.rightCoupons(options)
    this.setData({
      itemArry:options.item,
      goodsList:JSON.parse(options.item).items,
      totalPrice:JSON.parse(options.item).totalPrice,
      totalOriPrice:JSON.parse(options.item).totalOriPrice,
      orinDiscount:JSON.parse(options.item).orinDiscount,
      total_discount:JSON.parse(options.item).orinDiscount,
      total_fee:JSON.parse(options.item).totalPrice>0?JSON.parse(options.item).totalPrice:0,
      isDiscountTypeFlag:JSON.parse(options.item).items.some(item => (item['discountType'] !='' && item['discountType'] !=null) && item['discountType'] !=17  && item['discountType'] !=18 && item['discountType'] !=19 && item['discountType'] !=20),
      isAllDiscountTypeFlag:JSON.parse(options.item).items.every(item => item['discountType'] !='' && item['discountType'] !=null),
      isHaveCoupon:JSON.parse(options.item).items.some(item => item['iscoupon'] == 1),
      isOnlyCoupon:JSON.parse(options.item).items.every(item => item['iscoupon'] == 1 || item['productId'] == 114 || item['productId'] == 115 || item['productId'] == 116 || item['productId'] == 117)
    })
    if(!this.data.isOnlyCoupon && this.data.total_fee<39){
      this.setData(
        {
          money:(parseFloat(this.data.total_fee)+parseFloat(10)).toFixed(2),
        }
      )
    }else{
      this.setData({
        money:this.data.total_fee
      })
    }
    console.log(7878,this.data.isDiscountTypeFlag);
    
  },


  generateOrderId() {
    return this.getOrderNoFunc("yyyyMMddhhmmssS")+Math.floor(Math.random() * 89) + 10; // 组合时间戳和随机数
  },
  //支付
payOrder: function(event) {
  // console.log(111,event.currentTarget.dataset.type);
  let openid=wx.getStorageSync('openid')
  let phone=wx.getStorageSync('phone');
  // let dataArry=event.currentTarget.dataset.type.split(',')
  // console.log("orderId","");
  // console.log("text","测试商品");
  // console.log("total_fee","");
  // console.log("读取openid",openid);
  
  let orderId=this.generateOrderId()
  let text=orderId;
  let total_fee=this.data.money
  let _this=this
  wx.request({
    url: app.globalData.onlineUrl+'/wxpay',
    data: {
      Goods:{
        text:text,
        // 修复金额精度问题：先转换为数字再乘以100
        total_fee: Math.round(parseFloat(total_fee) * 100),
      },
      openid: openid,
      orderId:orderId,
      phone:phone,
    },
    header:{'content-type': 'application/json'},
    method:"POST",
    dataType:"json",
    success: res => {
      console.log(1,res.data.data.data)
      let result=res.data.data.data
      wx.requestPayment({
        timeStamp: result.timeStamp,
        nonceStr: result.nonceStr,
        package: result.package,
        signType: result.signType,
        paySign: result.paySign,
        success: res => {
          _this.insertCoupon();
          //处理会员权益
          _this.sendVipGift();
          wx.navigateTo({
            url: '/pages/state/state?type=1'
          })
        },
        fail: res => {
          console.log(3,res)
          wx.navigateTo({
            url: '/pages/state/state?type=2'
          })
        }
      })
    },
    complete: res => {
      this.addOrder(orderId);
      //处理购物车
      this.removeCar();
      this.updateInventory();
    }
  })
},
userCoupon(){
  if(this.data.currentCouId){
    let _this=this;
    wx.request({
      url: app.globalData.onlineUrl+'/userCoupon',
      data: {
        phone:wx.getStorageSync('phone'),
        id:_this.data.currentCouId,
      },
      header:{'content-type': 'application/json'},
      method:"POST",
      dataType:"json",
      success: res => {
      }
    })
  }
},
//删除购物车数据
removeCar(){
  let ids = this.data.goodsList.map(item => item.id);
  wx.request({
    url: app.globalData.onlineUrl+'/removeCar',
    data: {
      phone:wx.getStorageSync('phone'),
      ids:ids,
    },
    header:{'content-type': 'application/json'},
    method:"POST",
    dataType:"json",
    success: res => {
    }
  })
},
//送会员礼包
sendVipGift:async function () {
  let vip= this.data.goodsList.filter(item => item['productId'] == 114 || item['productId'] == 115 || item['productId'] == 116 || item['productId'] == 117)
  let _this=this;
  console.log(8866,vip);
  if (vip.length > 0) {
    // 使用for...of循环替代forEach，确保异步操作顺序执行
    for (const obj of vip) {
      console.log(888, obj);
      // 增加购买数量循环
      for (let a = 1; a <= obj.buyNum; a++) {
        // 等待当前VIP权益发送完成后再处理下一个
        await _this.sendVip(obj.productId);
      }
    }
  }
},
//给用户送会员权益
//给用户送会员权益
sendVip: function (id) {
  return new Promise((resolve, reject) => {
    let vipType = 0;
    switch(Number(id)) {
      case 114: vipType = 1; break;
      case 115: vipType = 2; break;
      case 116: vipType = 3; break;
      case 117: vipType = 4; break;
      default: 
        console.log('Invalid VIP product id:', id);
        reject(new Error('无效的会员产品ID'));
        return;
    }
    
    const phone = wx.getStorageSync('phone');
    wx.request({
      url: app.globalData.onlineUrl + '/vip/buy',
      data: {
        phone: phone,
        vipType: vipType,
      },
      header: {'content-type': 'application/json'},
      method: "POST",
      dataType: "json",
      success: res => {
        console.log('VIP发送成功:', res);
        resolve(res);
      },
      fail: err => {
        console.error('VIP发送失败:', err); // 添加错误日志
        reject(err); // 仅在失败时reject
      },
      // 移除complete回调，避免状态冲突
    });
  });
},

//塞券
insertCoupon: function () {
  let coupons= this.data.goodsList.filter(item => item.iscoupon == 1)
  let _this=this;
  console.log(8866,coupons);
  if(coupons.length!=0){
    coupons.forEach(function(obj) {
      console.log(888,obj)
      for(let a = 1; a<=obj.buyNum;a++){
        _this.sendQuan(obj.productId);
      }
    });
  }
},
//给用户送券
sendQuan(couponId){
  let _this=this;
  wx.request({
    url: app.globalData.onlineUrl+'/addCouponForUser',
    data: {
      phone:wx.getStorageSync('phone'),
      couponId:couponId,
    },
    header:{'content-type': 'application/json'},
    method:"POST",
    dataType:"json",
    success: res => {
    }
  })
},
//处理库存
updateInventory(){
  this.data.goodsList.forEach(good => {
    // 计算新库存：原库存 - 购买数量
    const newInventory = good.inventory - good.buyNum;
    // 调用后端接口更新库存
    console.log("库存处理",newInventory);
    this.setInventory(good.productId, newInventory);
  });
},
//修改库存
setInventory(id,newInventory){
  let _this=this;
  wx.request({
    url: app.globalData.onlineUrl+'/updateInventory', 
    method: 'POST',
    data: {
      id:id,
      inventory:newInventory,
    },
    success: function(res) {
      console.log("库存处理成功");
    },
    fail: function(err) {
    },
    complete: function() {}
  });
},
  //新增订单
addOrder: function (orderId) {
  let phone=wx.getStorageSync('phone');
  let _this=this
  // const coupon =this.data.coupons.find(item => item.id === this.data.currentCouId)
  wx.request({
    url: app.globalData.onlineUrl+'/addNewOrder',
    data: {
      orderId:orderId,
      phone:phone,
      totalPrice:_this.data.totalPrice,
      totalDiscount:_this.data.total_discount,
      totalFee:_this.data.money,
      couponId:_this.data.currentCouId?_this.data.coupons.find(item => item.id == _this.data.currentCouId).couponId:null,
      goodsJson:JSON.stringify(_this.data.goodsList),
      payTime:this.getDateNow(),
      consigneeId:_this.data.currentId?_this.data.currentId:null, 
      consigneeName:_this.data.consigneeName, 
      consigneePhone: _this.data.consigneePhone, 
      currentAddress:_this.data.currentAddress, 
      isOnlyCoupon:_this.data.isOnlyCoupon?'1':'0',
      giftName:_this.data.giftName,
      giftUrl:_this.data.giftUrl
    },
    header:{'content-type': 'application/json'},
    method:"POST",
    dataType:"json",
    success: res => {
      console.log("成功")
      //使用券
      _this.userCoupon()
    }
  })
},
//获取时间
getDateNow: function(){
  const now = new Date();
  const year = now.getFullYear();
  const month = ('0' + (now.getMonth() + 1)).slice(-2);
  const day = ('0' + now.getDate()).slice(-2);
  const hours = ('0' + now.getHours()).slice(-2);
  const minutes = ('0' + now.getMinutes()).slice(-2);
  const seconds = ('0' + now.getSeconds()).slice(-2);
  return year +'-'+ month+'-'+ day +' '+ hours +':'+ minutes +':'+ seconds;
},
  getOrderNoFunc(fmt){
    let date=new Date();
    var o = {
      "M+" : date.getMonth()+1,                 //月份
      "d+" : date.getDate(),                    //日
      "h+" : date.getHours(),                   //小时
      "m+" : date.getMinutes(),                 //分
      "s+" : date.getSeconds(),                 //秒
      "q+" : Math.floor((date.getMonth()+3)/3), //季度
      "S"  : date.getMilliseconds()             //毫秒
    };
  
    if(/(y+)/.test(fmt)){
      fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
          
    for(var k in o){
      if(new RegExp("("+ k +")").test(fmt)){
        fmt = fmt.replace(
          RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));  
      }       
    }
  
    return fmt;        
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
   this.getUserVip();
  },
  getUserVip(){
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/getUserVip",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{
        phone:wx.getStorageSync('phone')
      },
      dataType:"json",
      success:function(result) {
        //存储用户会员信息
        if(result.data.data.length>0){
          _this.setData({
            vipFlag:true
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    //监听页面卸载
    let pages = getCurrentPages().length - 1;
      console.log('需要销毁的页面：'+pages);
      wx.navigateBack({
        delta: pages
      })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})